/**
 * 自定义公共基础信息提示模块
 */
layui.define(['layer'], function (exports) {
    "use strict";
    var $ = layui.jquery,
        layer = layui.layer,
        globalParam = window.globalParam || {};
    var CmsCommon = {
        /**
         * 抛出异常错误信息
         * @param {String} msg
         */
        cmsError: function (msg, title) {
            parent.layer.alert(msg, {
                title: title,
                icon: 2,
                time: 0,
                resize: false,
                zIndex: layer.zIndex
            });
            return;
        },
        cmsInfo: function (msg, title, func) {
            var defaultFunc = function (index) {
                parent.layer.close(index);
            };
            parent.layer.alert(msg, {
                title: title,
                icon: 6,
                time: 0,
                resize: false,
                zIndex: layer.zIndex
            }, func || defaultFunc);
            return;
        },
        cmsOpen: function (option) {
            var defaults = {
                title: "", content: "", width: "", height: ""
            };
            var setting = $.extend({}, defaults, option);
            if (!setting.content) {
                CmsCommon.cmsError("弹出层内容为空", "错误信息");
                return false;
            }
            if (!setting.width) {
                setting.width = $(window).width() * 0.9;
            }
            if (!setting.height) {
                setting.height = $(window).height() * 0.8;
            }
            layer.open({
                type: 2,
                area: [setting.width + 'px', setting.height + 'px'],
                fix: false,
                /*maxmin: true,*/
                shadeClose: false,
                shade: 0.4,
                title: setting.title,
                content: setting.content
            });
            return;
        },
        cmsAjax: function (option) {
            var defaults = {
                scope: globalParam.getScope(),
                url: undefined,
                data: undefined,
                contentType: "application/json",// 发送信息至服务器时内容编码类型"application/x-www-form-urlencoded",
                dataType: "json",// 服务器返回json格式数据
                type: "POST",
                async: true,
                timeout: 60000,
                successFunc: undefined,
                errorFunc: undefined,
                error: undefined
            };
            var setting = $.extend({}, defaults, option);
            var load_layer = null;
            if (!setting.url) {
                CmsCommon.cmsError("请求地址为空", "错误信息");
                setting.errorFunc && setting.errorFunc();
                return;
            }
            if (setting.scope == 'test') {
                $.getJSON(setting.url, function (response) {
                    setting.successFunc && setting.successFunc(response);
                    load_layer && layer.close(load_layer);
                });
                return;
            }
            $.ajax({
                url: setting.url,
                data: JSON.stringify(setting.data),
                contentType: setting.contentType,
                dataType: setting.dataType,
                type: setting.type,
                async: setting.async,
                timeout: setting.timeout,
                beforeSend: function () {
                    load_layer = layer.msg("操作中...", {
                        time: 0,
                        shade: [0.3, '#393D49'],
                        icon: 4
                    });
                },
                success: function (response) {
                    if (!response || response.code != '0') {
                        CmsCommon.cmsError(response.msg || "操作失败", "错误信息");
                        if (setting.errorFunc !== undefined) {
                            setting.errorFunc(response);
                            return;
                        }
                        return;
                    }
                    setting.successFunc && setting.successFunc(response);
                },
                error: function (XMLHttpRequest, textStatus, errorThrown) {
                    if (setting.error !== undefined) {
                        setting.error(XMLHttpRequest, textStatus, errorThrown);
                        return;
                    }
                    CmsCommon.cmsError("系统错误", "错误信息");
                },
                complete: function (XMLHttpRequest, textStatus) {
                    load_layer && layer.close(load_layer);
                }
            });
        },
        cmsInArry: function (element, array) {
            for (var i = 0; i < array.length; i++) {
                if (array[i] == element) {
                    return true;
                }
            }
            return false;
        },
        //key 是否在  array[{targetKey:value}] 内
        cmsInArrayTwo: function (val, targetKey, array) {
            for (var i = 0; i < array.length; i++) {
                if (array[i][targetKey] != undefined && array[i][targetKey] != "" && array[i][targetKey] == val) {
                    return true;
                }
            }
            return false;
        },
        //key 在  array[{targetKey:value}] 内的下标
        cmsInArrayIndexTwo: function (val, targetKey, array) {
            for (var i = 0; i < array.length; i++) {
                if (array[i][targetKey] != undefined && array[i][targetKey] != "" && array[i][targetKey] == val) {
                    return i;
                }
            }
            return -1;
        },
        dateFormat: function (date, format) {
            format = typeof (format) == "string" ? format : "yyyy-MM-dd";
            if (date instanceof Date) {
                // do nothing
            } else if (!isNaN(date) && date != "") {
                date = new Date(date);
            } else {
                return date;
            }
            var o = {
                "M+": date.getMonth() + 1, // month
                "d+": date.getDate(), // day
                "h+": date.getHours(), // hour
                "m+": date.getMinutes(), // minute
                "s+": date.getSeconds(), // second
                "q+": Math.floor((date.getMonth() + 3) / 3), // quarter
                "S": date.getMilliseconds()
            };
            if (/(y+)/.test(format))
                format = format.replace(RegExp.$1, (date.getFullYear() + "")
                    .substr(4 - RegExp.$1.length));
            for (var k in o)
                if (new RegExp("(" + k + ")").test(format))
                    format = format.replace(RegExp.$1, RegExp.$1.length == 1 ? o[k]
                        : ("00" + o[k]).substr(("" + o[k]).length));
            return format;
        },
        hoverTip: function (option) {
            /*使用方式
            common.hoverTip({
                element : ".tipClassSoftware"
            });
            common.hoverTip();*/
            var defaults = {
                element: ".tipClassSoftware",//默认class名称
                time: 750
            };
            var setting = $.extend({}, defaults, option);
            if (!setting.element) {
                return;
            }
            var $this = $(setting.element);
            $this.each(function () {
                var $inThis = $(this), timer;
                $inThis.unbind("mouseenter mouseleave");
                $inThis.hover(function () {
                    var inThis = this;
                    timer = setTimeout(function () {
                        if (inThis.innerText || inThis.innerHTML || inThis.value) {
                            layer.tips(inThis.innerText || inThis.innerHTML || inThis.value, inThis, {
                                tips: 1,
                                time: 0
                            });
                        }
                    }, setting.time);
                }, function () {
                    clearTimeout(timer);
                    layer.closeAll('tips');
                });
            });
        },
        getQueryString: function (name) {
            var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
            var r = window.location.search.substr(1).match(reg);
            if (r != null) return window.decodeURI(unescape(r[2]));
            return null;
        },
        uuid: function (len, radix) {
            var chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split('');
            var uuid = [], i;
            radix = radix || chars.length;

            if (len) {
                // Compact form
                for (i = 0; i < len; i++) uuid[i] = chars[0 | Math.random() * radix];
            } else {
                // rfc4122, version 4 form
                var r;

                // rfc4122 requires these characters
                uuid[8] = uuid[13] = uuid[18] = uuid[23] = '-';
                uuid[14] = '4';

                // Fill in random data.  At i==19 set the high bits of clock sequence as
                // per rfc4122, sec. 4.1.5
                for (i = 0; i < 36; i++) {
                    if (!uuid[i]) {
                        r = 0 | Math.random() * 16;
                        uuid[i] = chars[(i == 19) ? (r & 0x3) | 0x8 : r];
                    }
                }
            }
            return uuid.join('');
        }
    };

    exports('common', CmsCommon);
});